import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Button,
  Table,
  Pagination,
  Switch,
  Image,
  Modal,
  message,
  Upload,
  Select,
  Space,
  Typography,
  Row,
  Col
} from 'antd';
import { SearchOutlined, PlusOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { useModel } from 'umi';
import { pictureApi } from '../../../api/url/index';
import {
  accountApi,
  accountDeleteApi,
  accountDetailApi,
  accountAddEditApi
} from '../../../api/permissions/index';
import styles from './index.module.css';

const { Search } = Input;
const { confirm } = Modal;
const { Title, Text } = Typography;

interface TableRow {
  id: number;
  account: string;
  img?: string;
  name?: string;
  status: number;
  create_time?: string;
  type: number;
  description?: string;
  manage_p?: number;
  manage_l?: number;
  manage_x?: number;
  roleid?: number;
}

interface Role {
  id: number;
  name: string;
  type: number;
}

interface FormData {
  id: number;
  account: string;
  roleid: number;
  type: number;
  password: string;
  img: string;
  status: number;
  pid: number;
  manage_p: number | string;
  manage_l: number | string;
  manage_x: number | string;
  description: string;
  confirmPassword: string;
}

const AccountManagement: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const [form] = Form.useForm();

  const [tableData, setTableData] = useState<TableRow[]>([]);
  const [roleList, setRoleList] = useState<Role[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('新增账户');
  const [searchText, setSearchText] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [formData, setFormData] = useState<FormData>({
    id: 0,
    account: '',
    roleid: 0,
    type: 0,
    password: '',
    img: '',
    status: 1,
    pid: 0,
    manage_p: '',
    manage_l: '',
    manage_x: '',
    description: '',
    confirmPassword: ''
  });

  // 过滤数据
  const filteredData = tableData.filter(row =>
    row.account.toLowerCase().includes(searchText.toLowerCase())
  );

  // 分页数据
  const currentPageData = filteredData.slice(
    (currentPage - 1) * pageSize,
    currentPage * pageSize
  );

  // 获取账户列表
  const getAccountList = async () => {
    setLoading(true);
    try {
      const res = await accountApi().signIn({});
      setTableData(res.data || []);
    } catch (err: any) {
      message.error('获取账户列表失败：' + (err.msg || '网络异常'));
    } finally {
      setLoading(false);
    }
  };

  // 获取角色列表
  const getRoleList = async () => {
    try {
      const res = await accountDetailApi().signIn({});
      setRoleList(res.data || []);
    } catch (err: any) {
      console.error('获取角色列表失败：', err);
      message.error('获取角色列表失败：' + (err.msg || '网络异常'));
    }
  };

  useEffect(() => {
    getAccountList();
    getRoleList();
  }, []);

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchText(value);
    setCurrentPage(1);
  };

  // 处理分页大小变化
  const handleSizeChange = (current: number, size: number) => {
    setPageSize(size);
    setCurrentPage(1);
  };

  // 处理页码变化
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  // 新增账户
  const handleAdd = () => {
    setModalTitle('新增账户');
    const initData: FormData = {
      id: 0,
      account: '',
      roleid: 0,
      type: 0,
      password: '',
      img: '',
      status: 1,
      pid: 0,
      manage_p: '',
      manage_l: '',
      manage_x: '',
      description: '',
      confirmPassword: ''
    };
    setFormData(initData);
    form.resetFields();
    setModalVisible(true);
  };

  // 编辑账户
  const handleEdit = (row: TableRow) => {
    setModalTitle('编辑账户');
    const matchedRole = roleList.find(r => r.id === row.roleid) ||
      roleList.find(r => r.type === row.type);
    
    const editData: FormData = {
      id: row.id,
      account: row.account,
      roleid: matchedRole ? matchedRole.id : 0,
      type: matchedRole ? matchedRole.type : 0,
      password: '', // 编辑时密码非必填，清空
      img: row.img || '',
      status: row.status,
      pid: 0,
      manage_p: row.manage_p || '',
      manage_l: row.manage_l || '',
      manage_x: row.manage_x || '',
      description: row.description || '',
      confirmPassword: ''
    };
    
    setFormData(editData);
    // 同步表单字段（关键修复：确保所有字段都同步到表单）
    form.setFieldsValue({
      account: row.account,
      roleid: matchedRole ? matchedRole.id : 0,
      password: '',
      img: row.img || '',
      status: row.status === 1,
      manage_p: row.manage_p || '',
      manage_l: row.manage_l || '',
      manage_x: row.manage_x || '',
      description: row.description || '',
      confirmPassword: ''
    });

    setModalVisible(true);
  };

  // 删除账户
  const handleDelete = (row: TableRow) => {
    confirm({
      title: '删除确认',
      content: `确定要删除账号「${row.account}」吗？`,
      okText: '确定',
      cancelText: '取消',
      okType: 'danger',
      centered: true,
      onOk: async () => {
        try {
          await accountDeleteApi().signIn({ id: row.id });
          message.success('删除成功');
          getAccountList();
        } catch (err: any) {
          message.error('删除失败：' + (err.msg || '网络异常'));
        }
      }
    });
  };

  // 处理角色选择变化（关键修复：同步表单的type字段）
  const handleRoleChange = (value: number) => {
    const matchedRole = roleList.find(role => role.id === value);
    const newType = matchedRole ? matchedRole.type : 0;
    setFormData(prev => ({
      ...prev,
      roleid: value,
      type: newType
    }));
    // 同步到表单字段，确保校验能获取到type值
    form.setFieldsValue({ type: newType });
  };

  // 上传图片（关键修复：同步表单的img字段）
  const handleCustomUpload = async (options: any) => {
    try {
      const file = options.file;
      const uploadFormData = new FormData();
      uploadFormData.append('file', file);
      const response = await pictureApi().signIn(uploadFormData);
      if (response.code === 1 || response.code === 200) {
        const imgUrl = response.url;
        setFormData(prev => ({ ...prev, img: imgUrl }));
        // 同步到表单字段，确保校验通过
        form.setFieldsValue({ img: imgUrl });
        message.success('上传成功');
      } else {
        message.error('上传失败：' + (response.msg || '未知错误'));
      }
    } catch (err: any) {
      message.error('上传失败：' + (err.msg || '网络异常'));
    }
  };

  // 账号状态变更
  const handleStatusChange = async (checked: boolean, row: TableRow) => {
    const newStatus = checked ? 1 : 2;
    const statusText = checked ? '开启' : '停用';

    // 本地临时更新状态
    const updatedData = tableData.map(item =>
      item.id === row.id ? { ...item, status: newStatus } : item
    );
    setTableData(updatedData);

    try {
      await accountAddEditApi().signIn({ ...row, status: newStatus });
      message.success(`账号已${statusText}`);
    } catch (err: any) {
      message.error(`更新为${statusText}失败：` + (err.msg || '网络异常'));
      setTableData([...tableData]); // 失败回滚
    }
  };

  // 提交表单（核心修复：字段同步、类型转换、参数处理）
  const handleSubmit = async () => {
    try {
      // 1. 表单校验（会触发所有必填项校验）
      const values = await form.validateFields();
      console.log('表单校验通过，提交参数：', values);

      // 2. 处理提交数据（类型转换 + 字段整合）
      const submitData = {
        id: formData.id, // 区分新增/编辑（id=0为新增）
        account: values.account.trim(),
        roleid: values.roleid,
        type: formData.type, // 从formData获取（角色选择时已同步）
        password: values.password || '', // 编辑时可为空
        img: values.img || '',
        status: values.status ? 1 : 2,
        pid: 0, // 若接口不需要可删除，需要则根据实际需求赋值
        // 管理费字段：字符串转数字（兼容空值）
        manage_p: values.manage_p ? parseFloat(values.manage_p) : 0,
        manage_l: values.manage_l ? parseFloat(values.manage_l) : 0,
        manage_x: values.manage_x ? parseFloat(values.manage_x) : 0,
        description: values.description || '',
        // 新增时才需要confirmPassword（接口通常不需要，仅前端校验）
      };

      // 3. 调用接口提交
      await accountAddEditApi().signIn(submitData);
      message.success(modalTitle === '新增账户' ? '添加成功' : '编辑成功');
      
      // 4. 重置状态
      setModalVisible(false);
      form.resetFields();
      getAccountList(); // 刷新列表
    } catch (error: any) {
      // 5. 错误处理（区分表单校验失败和接口失败）
      console.error(`${modalTitle}失败：`, error);
      if (error?.errorFields) {
        message.error('表单填写有误，请检查必填项和格式要求');
      } else {
        message.error(`${modalTitle}失败：` + (error.msg || '网络异常'));
      }
    }
  };

  // 重置表单
  const resetForm = () => {
    form.resetFields();
    setModalVisible(false);
  };

  // 表格列定义
  const columns: ColumnsType<TableRow> = [
    {
      title: '序号',
      align: 'center',
      width: 60,
      render: (_, __, index) => (currentPage - 1) * pageSize + index + 1
    },
    {
      title: '账号名称',
      dataIndex: 'account',
      align: 'center'
    },
    {
      title: '账号头像',
      dataIndex: 'img',
      align: 'center',
      render: (img) =>
        img ? (
          <Image
            width={45}
            height={45}
            src={img}
            preview={{ src: img }}
            alt="头像"
            className={styles.avatar}
          />
        ) : (
          <div className={styles.noAvatar}>暂无头像</div>
        )
    },
    {
      title: '角色类型',
      dataIndex: 'type',
      align: 'center',
      render: (type) => {
        const typeMap: { [key: number]: string } = {
          1: '超管',
          2: '劳务公司',
          3: '薪资审核员',
          4: '项目部'
        };
        const label = typeMap[type] || '未知';
        const isAuditor = label === '薪资审核员';
        return (
          <span className={isAuditor ? styles.auditorTag : styles.roleTag}>
            {label}
          </span>
        );
      }
    },
    {
      title: '角色名称',
      dataIndex: 'name',
      align: 'center',
      render: (name) => name || '未知'
    },
    {
      title: '账号状态',
      dataIndex: 'status',
      align: 'center',
      render: (status, record) => (
        <Switch
          checked={status === 1}
          checkedChildren="开启"
          unCheckedChildren="停用"
          onChange={(checked) => handleStatusChange(checked, record)}
          className={styles.statusSwitch}
        />
      )
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      align: 'center',
      render: (time) => time || '未知'
    },
    {
      title: '操作',
      align: 'center',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="primary"
            size="small"
            onClick={() => handleEdit(record)}
            className={styles.editBtn}
          >
            编辑
          </Button>
          {record.id !== 1 && (
            <Button
              danger
              size="small"
              onClick={() => handleDelete(record)}
              className={styles.deleteBtn}
            >
              删除
            </Button>
          )}
        </Space>
      )
    }
  ];

  // 上传组件配置
  const uploadProps = {
    customRequest: handleCustomUpload,
    showUploadList: false,
    beforeUpload: (file: File) => {
      const isImage = file.type.startsWith('image/');
      if (!isImage) message.error('只能上传图片文件!');
      return isImage;
    }
  };

  return (
    <div className={styles.pageContainer}>
      <Card className={styles.containerCard} bordered={false}>
        <div className={styles.headerContainer}>
          <Title level={4} className={styles.pageTitle}>账户管理</Title>
        </div>

        <div className={styles.searchBar}>
          <Search
            placeholder="请输入账户名称"
            allowClear
            enterButton={<SearchOutlined />}
            onSearch={handleSearch}
            onChange={(e) => setSearchText(e.target.value)}
            value={searchText}
            className={styles.searchInput}
          />
          <Button
            type="primary"
            onClick={handleAdd}
            className={styles.addButton}
          >
            新增
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={currentPageData}
          rowKey="id"
          loading={loading}
          pagination={false}
          size="middle"
          bordered
          className={styles.dataTable}
        />

        <div className={styles.paginationContainer}>
          <Pagination
            current={currentPage}
            pageSize={pageSize}
            total={filteredData.length}
            pageSizeOptions={[10, 20, 50, 100, 200]}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `共 ${total} 条`}
            onChange={handlePageChange}
            onShowSizeChange={handleSizeChange}
          />
        </div>
      </Card>

      {/* 新增/编辑弹窗（修复管理费区域布局和校验） */}
      <Modal
        title={modalTitle}
        open={modalVisible}
        onCancel={resetForm}
        centered
        footer={[
          <Button key="cancel" onClick={resetForm}>取消</Button>,
          <Button key="submit" type="primary" onClick={handleSubmit}>确定</Button>
        ]}
        width={1000}
        className={styles.modalForm}
        destroyOnClose // 关闭弹窗时销毁组件，避免缓存导致的字段异常
      >
        <Form
          form={form}
          layout="horizontal"
          className={styles.formContainer}
          initialValues={{ status: true }} // 默认开启状态
        >
          {/* 单列布局 - 统一labelCol和wrapperCol，确保对齐 */}
          <Form.Item
            label="账户名称"
            name="account"
            labelCol={{ span: 2 }}
            wrapperCol={{ span: 22 }}
            rules={[
              { required: true, message: '请输入账户名称' },
              { max: 50, message: '账户名称最多50个字符' }
            ]}
            className={styles.formItem}
          >
            <Input placeholder="请输入账户名称" maxLength={50} />
          </Form.Item>

          <Form.Item
            label="账户角色"
            name="roleid"
            labelCol={{ span: 2 }}
            wrapperCol={{ span: 22 }}
            rules={[
              { required: true, message: '请选择账户角色' },
              // 校验角色选择后type是否有效
              () => ({
                validator(_, value) {
                  if (value && formData.type) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('请选择有效的角色'));
                }
              })
            ]}
            className={styles.formItem}
          >
            <Select
              placeholder="请选择账户角色"
              onChange={handleRoleChange}
              options={roleList.map(role => ({
                label: role.name,
                value: role.id
              }))}
              showSearch // 支持搜索角色
            />
          </Form.Item>

          <Form.Item
            label="账户密码"
            name="password"
            labelCol={{ span: 2 }}
            wrapperCol={{ span: 22 }}
            rules={[
              { required: modalTitle === '新增账户', message: '请输入账户密码' },
              { pattern: /^\d+$/, message: '密码只能包含数字' },
              { min: 6, message: '密码长度至少6位' },
              { max: 20, message: '密码长度最多20位' }
            ]}
            className={styles.formItem}
          >
            <Input.Password
              placeholder={modalTitle === '新增账户' ? '请输入6-20位数字密码' : '不修改请留空'}
              onChange={(e) => {
                const value = e.target.value.replace(/[^\d]/g, '');
                form.setFieldValue('password', value);
              }}
            />
          </Form.Item>

          {modalTitle === '新增账户' && (
            <Form.Item
              label="确认密码"
              name="confirmPassword"
              labelCol={{ span: 2 }}
              wrapperCol={{ span: 22 }}
              rules={[
                { required: true, message: '请再次输入密码' },
                { pattern: /^\d+$/, message: '密码只能包含数字' },
                { min: 6, message: '密码长度至少6位' },
                { max: 20, message: '密码长度最多20位' },
                // 密码一致性校验（仅前端）
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value) return Promise.resolve();
                    if (value === getFieldValue('password')) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次密码输入不一致'));
                  }
                })
              ]}
              className={styles.formItem}
            >
              <Input.Password
                placeholder="请再次输入密码"
                onChange={(e) => {
                  const value = e.target.value.replace(/[^\d]/g, '');
                  form.setFieldValue('confirmPassword', value);
                }}
              />
            </Form.Item>
          )}

          <Form.Item
            label="账户头像"
            name="img"
            labelCol={{ span: 2 }}
            wrapperCol={{ span: 22 }}
            rules={[{ required: true, message: '请上传账户头像' }]}
            className={styles.formItem}
          >
            <Upload {...uploadProps}>
              <div className={styles.uploadArea}>
                {formData.img ? (
                  <img
                    src={formData.img}
                    alt="头像"
                    className={styles.uploadedImage}
                  />
                ) : (
                  <div className={styles.uploadPlaceholder}>
                    <PlusOutlined style={{ fontSize: '24px', color: '#999' }} />
                    <span className={styles.uploadText}>点击上传头像</span>
                  </div>
                )}
              </div>
            </Upload>
          </Form.Item>

          {/* 管理费区域 */}
          {formData.type === 2 && (
            <Form.Item
              labelCol={{ span: 2 }}
              wrapperCol={{ span: 22 }}
              className={styles.formItem}
            >
              <Row gutter={32} className={styles.feeRow}>
                {/* 长期管理费 - 统一labelCol，确保校验生效 */}
                <Col span={8}>
                  <Form.Item
                    name="manage_p"
                    label="长期管理费"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    rules={[
                      { required: true, message: '请输入' },
                      { pattern: /^\d+(\.\d{1,2})?$/, message: '只能输入数字，最多两位小数' },
                      {
                        validator: (_, value) => {
                          if (value && parseFloat(value) > 100) {
                            return Promise.reject(new Error('不能超过100%'));
                          }
                          return Promise.resolve();
                        }
                      }
                    ]}
                  >
                    <Input
                      placeholder="例如：5.5"
                      maxLength={10}
                      onChange={(e) => {
                        let value = e.target.value.replace(/[^\d.]/g, '');
                        const parts = value.split('.');
                        if (parts.length > 2) value = parts[0] + '.' + parts.slice(1).join('');
                        if (parts.length === 2 && parts[1].length > 2) value = parts[0] + '.' + parts[1].slice(0, 2);
                        form.setFieldValue('manage_p', value);
                      }}
                    />
                  </Form.Item>
                </Col>

                <Col span={8}>
                  <Form.Item
                    name="manage_l"
                    label="短期管理费"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    rules={[
                      { required: true, message: '请输入' },
                      { pattern: /^\d+(\.\d{1,2})?$/, message: '只能输入数字，最多两位小数' },
                      {
                        validator: (_, value) => {
                          if (value && parseFloat(value) > 100) {
                            return Promise.reject(new Error('不能超过100%'));
                          }
                          return Promise.resolve();
                        }
                      }
                    ]}
                  >
                    <Input
                      placeholder="例如：3.8"
                      maxLength={10}
                      onChange={(e) => {
                        let value = e.target.value.replace(/[^\d.]/g, '');
                        const parts = value.split('.');
                        if (parts.length > 2) value = parts[0] + '.' + parts.slice(1).join('');
                        if (parts.length === 2 && parts[1].length > 2) value = parts[0] + '.' + parts[1].slice(0, 2);
                        form.setFieldValue('manage_l', value);
                      }}
                    />
                  </Form.Item>
                </Col>

                <Col span={8}>
                  <Form.Item
                    name="manage_x"
                    label="学员管理费"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    rules={[
                      { required: true, message: '请输入' },
                      { pattern: /^\d+(\.\d{1,2})?$/, message: '只能输入数字，最多两位小数' },
                      {
                        validator: (_, value) => {
                          if (value && parseFloat(value) > 100) {
                            return Promise.reject(new Error('不能超过100%'));
                          }
                          return Promise.resolve();
                        }
                      }
                    ]}
                  >
                    <Input
                      placeholder="例如：2.0"
                      maxLength={10}
                      onChange={(e) => {
                        let value = e.target.value.replace(/[^\d.]/g, '');
                        const parts = value.split('.');
                        if (parts.length > 2) value = parts[0] + '.' + parts.slice(1).join('');
                        if (parts.length === 2 && parts[1].length > 2) value = parts[0] + '.' + parts[1].slice(0, 2);
                        form.setFieldValue('manage_x', value);
                      }}
                    />
                  </Form.Item>
                </Col>
              </Row>
            </Form.Item>
          )}

          <Form.Item
            label="账号状态"
            name="status"
            labelCol={{ span: 2 }}
            wrapperCol={{ span: 22 }}
            valuePropName="checked"
            className={styles.formItem}
          >
            <Switch checkedChildren="开启" unCheckedChildren="停用" />
          </Form.Item>

          <Form.Item
            label="公司介绍"
            name="description"
            labelCol={{ span: 2 }}
            wrapperCol={{ span: 22 }}
            className={styles.formItem}
            rules={[{ max: 500, message: '最多输入500个字符' }]}
          >
            <Input.TextArea
              placeholder="请输入公司介绍内容（可选）"
              rows={4}
              showCount
              maxLength={500}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default AccountManagement;